package com.yugu.park.security.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;

import com.yugu.park.manage.AsyncManager;
import com.yugu.park.manage.factory.AsyncFactory;
import com.yugu.util.Constants;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import com.yugu.park.config.TokenService;
import com.yugu.park.exception.BusinessException;
import com.yugu.park.security.entity.LoginUser;
import com.yugu.park.security.entity.TSysMenu;
import com.yugu.park.security.entity.TSysUser;
import com.yugu.park.security.mapper.TSysUserMapper;
import com.yugu.park.security.service.TSysUserService;
import com.yugu.util.SecurityUtils;
@Service
public class TSysUserServiceImpl implements TSysUserService {
	@Resource
	private TSysUserMapper mapper;
	@Resource
	private AuthenticationManager authenticationManager;
	@Resource
	private TokenService tokenService;
	@Override
	public TSysUser selectUserByUserName(String username) {
		return mapper.selectUserByUserName(username);
	}
	@Override
	public String login(String username, String password, String uuid) {
		// 用户离职不允许登录
		TSysUser sysUser = this.selectUserByUserName(username);
		if(sysUser==null) {
			throw new BusinessException("该用户不存在，请核实用户名！");
		}else {
			if(sysUser.getDelFlag()!=null&&sysUser.getDelFlag()==1) {
				throw new BusinessException("用户已失效");
			}
		}
		
		// 用户验证
		Authentication authentication = null;
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名密码错误"));
				throw new BusinessException("用户名密码错误!");
			} else {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new BusinessException(e.getMessage());
			}
		}
		AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		// 生成token
		return tokenService.createToken(loginUser);
}
	@Override
	public Set<String> getUserPermission() {
		Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
//        perms.addAll(mapper.selectAllPerms());
		TSysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (sysUser.getIsAdmin()!=null&&sysUser.getIsAdmin()) {
            perms.addAll(mapper.selectAllPerms());
        } else {
            perms.addAll(mapper.selectPermsByUserId(sysUser.getUserId()));
        }
        return perms;
	}
	@Override
	public List<TSysMenu> getRouters() {
		List<TSysMenu> result = new ArrayList<TSysMenu>();
		TSysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
		Map<String,String> param = new HashMap<String,String>();
        if (sysUser.getIsAdmin()!=null&&sysUser.getIsAdmin()){
        	param.put("userId", null);
        }else {
        	param.put("userId", sysUser.getUserId());
        }
        List<TSysMenu> list =mapper.getRouters(param);
        for(TSysMenu per:list) {
        	String pId = per.getParentId();
        	if ("0".equals(pId)) {
        		result.add(per);
            }
        	for(TSysMenu it:list) {
        		if (it.getParentId().equals(per.getMenuId())) {
                    if (per.getChildren() == null) {
                        per.setChildren(new ArrayList<TSysMenu>());
                    }
                    per.getChildren().add(it);
                }
        	}
        }
		return result;
	}

}
